import { createStore } from 'vuex'

export default createStore({
  state: {
    info: localStorage.getItem('info') ? JSON.parse(localStorage.getItem('info')) : []
  },
  getters: {
    // 获取总价
    total ( state ) {
        return state.info.reduce( ( pre, cur ) => {
          if ( cur.flag ) {
            pre += cur.price * cur.num;
        }
          return pre;
        }, 0 ) * 100;
    },
    // 获取全选状态
    checkAll (state) {
      return state.info.every( item => item.flag)
    }
  },
  mutations: {
    // 保存到vuex
    saveInfo ( state, payload ) {
      // 判断是否有相同的商品如果有那就数量加一没有就添加到数组里
      let index = state.info.findIndex( item => item.id == payload.id );
      if ( index == -1 ) {
        state.info.push( payload );
      } else {
        state.info[ index ].num++;
      }
      // 本地存储
      localStorage.setItem( 'info', JSON.stringify( state.info ) );
    },
    // 修改全选
    checkAll ( state, payload ) {
      state.info.forEach(item => item.flag = payload);
      // 本地存储
      localStorage.setItem( 'info', JSON.stringify( state.info ) );
    },
    // 删除
    del ( state, payload ) {
      let index = state.info.findIndex(item => item.id == payload.id)
      state.info.splice( index, 1 );
      // 本地存储
      localStorage.setItem( 'info', JSON.stringify( state.info ) );

    }
  },
  actions: {
  },
  modules: {
  }
})
